package com.aruba.paging.paging.model;

import androidx.annotation.NonNull;
import androidx.paging.PositionalDataSource;

import com.aruba.paging.api.RetrofitClient;
import com.aruba.paging.entity.Movie;
import com.aruba.paging.entity.Movies;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by aruba on 2021/9/17.
 */
public class MovieDataSource extends PositionalDataSource<Movie> {
    //一次取8条数据
    public static final int PER_PAGE = 8;

    //第一次加载
    @Override
    public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<Movie> callback) {
        int startPosition = 0;
        RetrofitClient.getInstance()
                .getApi()
                //入参：开始点，一次获取的数据量大小
                .getMovies(startPosition, PER_PAGE)
                .enqueue(new Callback<Movies>() {
                    @Override
                    public void onResponse(Call<Movies> call, Response<Movies> response) {
                        if (response.body() != null) {
                            //数据回调给pagedlist
                            callback.onResult(response.body().movies,
                                    response.body().start,
                                    response.body().total);
                        }
                    }

                    @Override
                    public void onFailure(Call<Movies> call, Throwable t) {

                    }
                });
    }

    //加载更多
    @Override
    public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<Movie> callback) {
        RetrofitClient.getInstance()
                .getApi()
                //入参：开始点，一次获取的数据量大小
                //加载更多时，params中的startPosition参数会自动加PER_PAGE
                .getMovies(params.startPosition, PER_PAGE)
                .enqueue(new Callback<Movies>() {
                    @Override
                    public void onResponse(Call<Movies> call, Response<Movies> response) {
                        if (response.body() != null) {
                            //数据回调给pagedlist
                            callback.onResult(response.body().movies);
                        }
                    }

                    @Override
                    public void onFailure(Call<Movies> call, Throwable t) {

                    }
                });
    }
}
